package cn.newgrand.netcall.integration.sms;

import java.awt.Color;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.MessageEventManager;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.util.ModelUtil;
import org.jivesoftware.spark.util.StringUtils;
import org.jivesoftware.spark.util.log.Log;
import org.jivesoftware.sparkimpl.plugin.alerts.MessageToTranscript;
import org.jivesoftware.sparkimpl.plugin.transcripts.ChatTranscripts;

import cn.newgrand.netcall.smackx.integration.AppSysBindPhoneIQ;
import cn.newgrand.smackx.packet.AppSysMes;

/**
 * @author SidneyRen E-mail:SidneyRen@hotmail.com
 * @version create time：2010-12-16 下午04:55:58
 * 类说明
 */
public class SMSManager {
	private static final String FILENAME="sms";
	private static SMSManager instance;
	private static Object LOCK = new Object();
	public static final String REPLY = "reply";
	public static final String UNREPLY = "unreply";
	
	//短信服务是否可用
	public static boolean isSMSServerAvailable;
	
	//是否被授予了发送短信权限
	public static boolean isGrantSendSMS;
	
	//用户绑定的手机号码(可能为空)
	public static String bindPhone;
	
	//用户离开的时间
	public static Map<String, Long> awayDateMap = new HashMap<String, Long>();
	
	
	private SMSManager(){
		
	}
	
	public static SMSManager getInstance(){
		synchronized (LOCK) {
			if(instance==null){
				return new SMSManager();
			}
			return instance;
		}
	}
	
	
    /**
     * Invites users to an existing room.
     *
     * @param serviceName the service name to use.
     * @param roomName    the name of the room.
     * @param jids        a collection of the users to invite.
     */
    public static void handleSMSDialog(Collection jids) {
        SMSPanel smsDialog = new SMSPanel();
        smsDialog.inviteUsersToRoom(jids);
    }
    
    public void sendSMS(SMS entity,String type) throws Exception{
    	String content = StringUtils.escapeForXML(entity.toXML());
    	sendSMS(content,type);
    }
    
    public void sendSMS(String content,String type) throws Exception{
    	
        final Message message = new Message();

//        if (threadID == null) {
//            threadID = StringUtils.randomString(6);
//        }
//        message.setThread(threadID);

        // Set the body of the message using typedMessage
        message.setBody(content);

        // IF there is no body, just return and do nothing
        if (!ModelUtil.hasLength(content)) {
            return;
        }

        // Fire Message Filters
//        SparkManager.getChatManager().filterOutgoingMessage(this, message);

        // Fire Global Filters
//        SparkManager.getChatManager().fireGlobalMessageSentListeners(this, message);

        sendSMS(message,type);

//        sendNotification = true;
    }

    /**
     * Sends a message to the appropriate jid. The message is automatically added to the transcript.
     *
     * @param message the message to send.
     */
    public void sendSMS(Message message,String type) throws Exception {
//        lastActivity = System.currentTimeMillis();

//        try {
//            getTranscriptWindow().insertMessage(getNickname(), message, ChatManager.TO_COLOR, Color.white);
//            getChatInputEditor().selectAll();

//            getTranscriptWindow().validate();
//            getTranscriptWindow().repaint();
//            getChatInputEditor().clear();
//        }
//        catch (Exception ex) {
//            Log.error("Error sending message", ex);
//        }

        // Before sending message, let's add our full jid for full verification
        message.setType(Message.Type.normal);
        message.setTo("sms@integration."+ SparkManager.getConnection().getServiceName());
        message.setFrom(SparkManager.getSessionManager().getJID());
        AppSysMes mes = new AppSysMes();
        mes.setType(type);
        message.addExtension(mes);

        // Notify users that message has been sent
//        fireMessageSent(message);

        //TODO 添加消息记录
//        addToTranscript(message, false);

//        getChatInputEditor().setCaretPosition(0);
//        getChatInputEditor().requestFocusInWindow();
//        scrollToBottom();

        // No need to request displayed or delivered as we aren't doing anything with this
        // information.
        MessageEventManager.addNotificationsRequests(message, true, false, false, true);
       
        // Send the message that contains the notifications request
//            fireOutgoingMessageSending(message);
        SparkManager.getConnection().sendPacket(message);
        
    }
    
    public void saveTranscript(String content){
    	Message temp = new Message();
    	temp.setBody(content);
    	ChatTranscripts.appendToTranscript(FILENAME,MessageToTranscript.messageToTranscript(temp));
    }
    
    public boolean isSMSServerAvailable(){
    	return isSMSServerAvailable;
    }
    
    public void setSMSServerAvailable(boolean isAvailable){
    	this.isSMSServerAvailable =  isAvailable;
    }
    
    public void init(){
    	
    }
    
    public void synUpdateUserPhone(String phone){
    	AppSysBindPhoneIQ bindPhoneIQ = new AppSysBindPhoneIQ();
		bindPhoneIQ.setBindPhone(phone);
		bindPhoneIQ.setBindType("updatePhone");
		bindPhoneIQ.setType(IQ.Type.SET);
		bindPhoneIQ.setTo("integration." + SparkManager.getConnection().getServiceName());
		SparkManager.getConnection().sendPacket(bindPhoneIQ);
    }
    
}
